package com.rdiot.yx485.ui.room

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import com.drake.brv.annotaion.DividerOrientation
import com.drake.brv.utils.*
import com.drake.net.utils.TipUtils
import com.drake.net.utils.scope
import com.drake.net.utils.scopeDialog
import com.drake.net.utils.scopeNetLife
import com.king.zxing.util.LogUtils
import com.lindroy.iosdialog.IAlertDialog
import com.rdiot.yx485.BuildConfig
import com.rdiot.yx485.R
import com.rdiot.yx485.base.BaseFragment
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.bean.RoomData
import com.rdiot.yx485.databinding.FraRoomBinding
import com.rdiot.yx485.databinding.ItemRoomBinding
import com.rdiot.yx485.net.delRoom
import com.rdiot.yx485.net.getFamilyData
import com.rdiot.yx485.net.setPower
import com.rdiot.yx485.ui.bind.BindActivity
import com.rdiot.yx485.ui.ctrl.RoomCtrlMainActivity
import com.rdiot.yx485.ui.main.MainActivity
import com.rdiot.yx485.util.RoomUtils
import com.rdiot.yx485.util.clearGoTo
import com.rdiot.yx485.util.curTime
import com.rdiot.yx485.util.getClearTopIntent
import com.rdiot.yx485.util.setClickLimitListener
import dagger.hilt.android.AndroidEntryPoint

/**
 * 房间
 * @author mR2hao
 * @date 2022/11/9
 */
@AndroidEntryPoint
class RoomFragment : BaseFragment<FraRoomBinding>() {
    override fun getLayoutId() = R.layout.fra_room
    private var dialog: IAlertDialog? = null

    private val resourceRoomDataList = mutableListOf<RoomData>()


    override fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) {
        binding.nb.setLeftClickListener {
            act.clearGoTo(BindActivity::class.java)
        }

        binding.nb.setRightClickListener {
            binding.rv.bindingAdapter.toggle()
        }

        binding.llAdd.setClickLimitListener {
            act.clearGoTo(BindActivity::class.java)
        }

        initRooms()
    }

    private fun initRooms() {
        binding.rv.grid(1).divider {
            setDrawable(R.drawable.divider_horizontal)
            orientation = DividerOrientation.GRID
            includeVisible = true
        }.setup {
            addType<RoomData>(R.layout.item_room)
            onBind {
                val itemRoomBinding = getBinding<ItemRoomBinding>()

                if (binding.rv.bindingAdapter.toggleMode) {
                    itemRoomBinding.ivDel.setClickLimitListener {
                        clickHandler(R.id.iv_del, this.modelPosition)
                    }
                } else {
                    itemRoomBinding.clItem.setClickLimitListener {
                        clickHandler(R.id.cl_item, this.modelPosition)
                    }

                    itemRoomBinding.ivSwitch.setClickLimitListener {
                        clickHandler(R.id.iv_switch, this.modelPosition)
                    }
                }

            }
            onToggle { position, toggleMode, _ ->
                //禁止下拉刷新
                binding.page.isEnabled = !toggleMode
                // 刷新列表显示选择按钮
                val model = getModel<RoomData>(position)
                model.isEditMode = toggleMode
                binding.rv.bindingAdapter.notifyItemChanged(position)


                setToggleModeDisplay(toggleMode)

                //编辑模式下 取消轮询
                LocalData.lastRefreshTime = if (toggleMode) Long.MAX_VALUE else 0
            }
        }

        LocalData.selFamilyId.observe(this) {
            if (!it.isNullOrBlank()) {
                binding.page.onRefresh {
                    scope {
                        getFamilyData().await().also {
                            LocalData.familyData.postValue(it)
                        }
//                        binding.rv.models = getFamilyData().await().room
//                        addData(getFamilyData().await().room) {
//                            index < 1
//                        }
                    }
                }.autoRefresh()
            }
        }


        LocalData.familyData.observe(this) { familyData ->
//            // 开启编辑模式 取消监听数据变化
//            if (binding.rv.bindingAdapter.toggleMode) {
//                return@observe
//            }

            familyData?.room?.let { roomData ->
                if (roomData.isEmpty()) {
                    binding.ivNoRoom.visibility = View.VISIBLE
                    binding.rv.visibility = View.GONE
                } else {
                    resourceRoomDataList.clear()
                    resourceRoomDataList.addAll(roomData)

                    resourceRoomDataList.forEach {
                        it.isEditMode = binding.rv.bindingAdapter.toggleMode
                        it.isInfrared = RoomUtils.isInfrared(it.code)
                        it.isWaterPlc = RoomUtils.isWaterSystem(it.code)
                        if (it.isOnline) {
                            it.onlineStr = "在线"
                        }
                    }

                    binding.rv.models = resourceRoomDataList

                    binding.ivNoRoom.visibility = View.GONE
                    binding.rv.visibility = View.VISIBLE
                }
            }
        }

    }

    private fun setToggleModeDisplay(toggleMode: Boolean) {
        //更改编辑按钮文本、文本颜色
        val id = if (toggleMode) R.string.finish else R.string.edit
        binding.nb.setRightBtnText(id)
        val color = if (toggleMode) R.color.login_btn_color else R.color.main_text_color
        binding.nb.setRightBtnTextColor(color)

        //隐藏底部Tab栏
        (act as MainActivity).hideBottomTabBar(toggleMode)
    }

    /**
     * 列表Item点击时间
     * @param viewId Int
     */
    private fun clickHandler(@IdRes viewId: Int, position: Int) {
        LocalData.lastRefreshTime = curTime
        val roomData = LocalData.familyData.value?.room?.get(position) ?: return

        when (viewId) {
            R.id.cl_item -> {
                act.getClearTopIntent(RoomCtrlMainActivity::class.java).apply {
                    putExtra(RoomCtrlMainActivity.ROOM_DATA, roomData)
                    act.clearGoTo(this)
                }
                LogUtils.i("onItemClicked:  $roomData")
            }
            R.id.iv_switch -> {
                roomData.power = !roomData.power
                scopeNetLife {
                    setPower(
                        LocalData.familyData.value?.gateway ?: "",
                        roomData
                    ).await()
                }
                LocalData.familyData.postValue(LocalData.familyData.value)
            }
            R.id.iv_del -> {
                showDelDialog(roomData)
            }
        }
    }

    private fun showDelDialog(roomData: RoomData) {
        dialog?.dismiss()
        dialog = IAlertDialog.build(this)
            .setTitle(R.string.hint)
            .setMessage(R.string.del_msg)
            .setCancelOutside(false)
            .setNegButtonText(R.string.cancel)
            .setNegButtonTextColor(resources.getColor(R.color.main_text_color, null))
            .setNegClickListener { dialogInterface ->
                dialogInterface.dismiss()
            }
            .setDismissible(false)
            .setAlpha(1.0F)
            .setPosButtonText(R.string.del)
            .setPosButtonTextColor(resources.getColor(R.color.warning, null))
            .setPosClickListener { dialogInterface ->
                dialogInterface.dismiss()
                LogUtils.d("删除房间 ${roomData.name} - ${roomData.homeId}")
                deleteRoom(roomData)
            }
        dialog?.show()
    }

    /** 删除房间 */
    private fun deleteRoom(roomData: RoomData) {
        scopeDialog(cancelable = BuildConfig.DEBUG) {
            delRoom(arrayListOf(roomData)).await()
            TipUtils.toast(getString(R.string.delete_success))
            LocalData.lastRefreshTime = 0

//            binding.rv.bindingAdapter.mutable.remove(roomData)
//            LocalData.familyData.value?.room =
//                binding.rv.bindingAdapter.mutable as MutableList<RoomData>
//
//            if (binding.rv.bindingAdapter.mutable.size == 0) {
//                binding.rv.bindingAdapter.toggle(false)
//                setToggleModeDisplay(false)
//            }
//
//            LocalData.familyData.postValue(LocalData.familyData.value)

        }
    }
}
